package com.comtime.info;

import java.io.IOException;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.webkit.ConsoleMessage;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.comtime.entity.NewListInfo;
import com.comtime.entity.PingLunListAdapter;
import com.comtime.entity.PinglunInfo;
import com.comtime.smartbox.Activity_1;
import com.comtime.smartbox.BaseActivity;
import com.comtime.smartkilimanjaro.R;
import com.comtime.utils.MyConfig;
import com.comtime.utils.MySharedPreferences;
import com.comtime.utils.Util;
import com.comtime.view.InfoListView;
import com.comtime.view.MyProgressDialog;
import com.comtime.view.SendPingLunPopwindow;
import com.comtime.view.SendPingLunPopwindow.OnClickListenterBack;
import com.comyou.comyouhttp.ComyouHttpCallBack;
import com.comyou.comyouhttp.ComyouHttpClient;
import com.comyou.comyouhttp.ComyouHttpProgram;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;

public class InfoActivity extends BaseActivity {

	WebView webView;
	ClipboardManager clipboard;
	xWebChromeClient xwebchromeclient;
	InfoListView listView;// 评论列表
	PingLunListAdapter pingLunListAdapter;// 评论布局器
	ArrayList<PinglunInfo> pinglunInfos = new ArrayList<PinglunInfo>();// 评论列表

	int news_id = 0;// 信息id
	int good_num = 0;// 点赞
	int total_count = 0;// 品论
	String sendTime = "";// 时间
	String title = "";// 
	// 开头
	TextView tv_title, tv_time, tv_good_num, tv_total_num;
	// 评论
	TextView tv_list_pinlun;
	//加载更多
	TextView tv_foot_show;
	RelativeLayout relate_foot_show;
	ProgressBar progressBar_foot_show;
	
	MySharedPreferences mySharedPreferences;
	boolean zanFlag=false;//是否点赞
	boolean pinglunCanFlag=true;//是否有评论权限
	boolean favFlag=false;//是否收藏过
	
	ImageButton zanImageButton,favImageButton;//点赞和收藏

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_info);
		mySharedPreferences=MySharedPreferences.getInstance(this);

		clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
		// 设置WebView属性，能够执行Javascript脚本
		webView = (WebView) findViewById(R.id.web_view);
		WebSettings settings = webView.getSettings();
		settings.setJavaScriptEnabled(true);

		settings.setJavaScriptCanOpenWindowsAutomatically(true);
		settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);

		// 加载需要显示的网页
		Intent intent = getIntent();
		NewListInfo newListInfo = (NewListInfo) intent
				.getSerializableExtra(Activity_1.INFOLISTS);
		news_id = newListInfo.getNews_id();
		String urlString = newListInfo.getNews_url();
		good_num = newListInfo.getGood_num();
		total_count = newListInfo.getTotal_count();
		sendTime = newListInfo.getAdd_time();
		title=newListInfo.getTitle();
		webView.loadUrl(urlString);
		// // 设置Web视图
		xwebchromeclient = new xWebChromeClient();

		webView.setWebViewClient(new WebViewClient());
		webView.setWebChromeClient(xwebchromeclient);
		webView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				// TODO Auto-generated method stub
				return false;
			}
		});
		if (savedInstanceState != null) {
			webView.restoreState(savedInstanceState);
		}
		init();
		updateUI();
		getInfo();
	}

	void init() {

		listView = (InfoListView) findViewById(R.id.listview);

		View view = LayoutInflater.from(this).inflate(R.layout.info_foot, null);
		relate_foot_show=(RelativeLayout) view.findViewById(R.id.relate_foot_show);
		tv_foot_show=(TextView) view.findViewById(R.id.tv_foot_show);
		progressBar_foot_show=(ProgressBar) view.findViewById(R.id.progressbar_foot_show);
		relate_foot_show.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				
				relate_foot_show.setEnabled(false);
				progressBar_foot_show.setVisibility(View.VISIBLE);
				tv_foot_show.setText(getText(R.string.loading));
				getInfo();
				
			}
		});
		tv_title = (TextView) findViewById(R.id.tv_title);
		tv_time = (TextView) findViewById(R.id.tv_time);
		tv_good_num = (TextView) findViewById(R.id.tv_good_num);
		tv_total_num = (TextView) findViewById(R.id.tv_total_num);

		listView.addFooterView(view);

		pingLunListAdapter = new PingLunListAdapter(this, pinglunInfos);
		listView.setAdapter(pingLunListAdapter);

		

		tv_list_pinlun = (TextView) findViewById(R.id.tv_list_pinlun_num);
		
		zanImageButton=(ImageButton) findViewById(R.id.image_zan);
		favImageButton=(ImageButton) findViewById(R.id.image_fav);
	}

	void updateUI() {
		tv_total_num.setText("" + total_count);
		tv_list_pinlun.setText("(" + total_count + ")");
		tv_good_num.setText("" + good_num);
		tv_time.setText("" + sendTime);
		tv_title.setText(title);
		
		if(zanFlag){
			zanImageButton.setImageResource(R.drawable.icon_btn_like_big_pre);
		}else{
			zanImageButton.setImageResource(R.drawable.icon_btn_like_big_nor);
		}
		
		if(favFlag){
			favImageButton.setImageResource(R.drawable.icon_btn_coll_big_pre);
		}else{
			favImageButton.setImageResource(R.drawable.icon_btn_coll_big_nor);
		}
	}

	// Web视图

	public class xWebChromeClient extends WebChromeClient {

		@Override
		public void onShowCustomView(View view,
				WebChromeClient.CustomViewCallback callback) {
			Log.i("tag", "sg*****************************");
		}

		@Override
		public void onHideCustomView() {
			Log.i("tag", "sg22222*****************************");
		}

		@Override
		public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
			// TODO Auto-generated method stub
			Log.d("ZR",
					consoleMessage.message() + " at "
							+ consoleMessage.sourceId() + ":"
							+ consoleMessage.lineNumber());
			return super.onConsoleMessage(consoleMessage);
		}
	}

	public void backAction(View v) {
		this.finish();
		overridePendingTransition(R.anim.enter_left, R.anim.exit_right);
	}

	
	/**
	 * 点赞
	 * 
	 * @param v
	 */
	public void LikeAction(View v) {
		if(!Util.hasNetwork(this)){
			showToast(getText(R.string.no_network).toString());
			return;
		}
		zanSend();
	}

	/**
	 * 评论
	 * 
	 * @param v
	 */
	public void CommentAction(View v) {
		if(!Util.hasNetwork(this)){
			showToast(getText(R.string.no_network).toString());
			return;
		}
		if(!pinglunCanFlag){
			showToast(getText(R.string.pinglun_can_not).toString());
			return;
		}
		sendSendPingLunPopwindow();
		
	}
	/**
	 * 收藏
	 * 
	 * @param v
	 */
	public void FavAction(View v) {
		if(!Util.hasNetwork(this)){
			showToast(getText(R.string.no_network).toString());
			return;
		}
		favSend();
	}

	/**
	 * 分享
	 * 
	 * @param v
	 */
	public void ShareAction(View v) {

		new ShareAction(this)
				.setDisplayList(SHARE_MEDIA.SINA, SHARE_MEDIA.QQ,
						SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN,
						SHARE_MEDIA.WEIXIN_CIRCLE)
				.setShareboardclickCallback(new ShareBoardlistener() {
					@Override
					public void onclick(SnsPlatform snsPlatform,
							SHARE_MEDIA share_media) {
						if (snsPlatform.mShowWord
								.equals("umeng_sharebutton_custom")) {
							Toast.makeText(InfoActivity.this,
									getText(R.string.copy_link).toString(),
									Toast.LENGTH_LONG).show();
							Uri copyUri = Uri.parse("http://www.baidu.com");
							ClipData clip = ClipData.newUri(
									getContentResolver(), "URI", copyUri);
							clipboard.setPrimaryClip(clip);

						} else {
							new ShareAction(InfoActivity.this)
									.withTitle(
											getText(R.string.app_name)
													.toString())
									.withText(
											getText(R.string.app_name)
													.toString())
									.setPlatform(share_media)
									.withTargetUrl("http://www.baidu.com")
									.setCallback(umShareListener).share();

						}
					}
				}).open();
	}

	private UMShareListener umShareListener = new UMShareListener() {
		@Override
		public void onResult(SHARE_MEDIA platform) {

			Toast.makeText(
					InfoActivity.this,
					platform + " " + getText(R.string.share_success).toString(),
					Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onError(SHARE_MEDIA platform, Throwable t) {
			Toast.makeText(InfoActivity.this,
					platform + " " + getText(R.string.share_fail).toString(),
					Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onCancel(SHARE_MEDIA platform) {
			Toast.makeText(InfoActivity.this,
					platform + " " + getText(R.string.share_cancel).toString(),
					Toast.LENGTH_SHORT).show();
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		/** attention to this below ,must add this **/
		UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
	}

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
				//加载信息成功
				
				if(pinglunInfos!=null){
					pinglunInfos.clear();
					pingLunListAdapter.notifyDataSetChanged();
				}
				
				
				if(pingArrayList!=null&&pingArrayList.size()>0){
					pinglunInfos.addAll(pingArrayList);
					pingLunListAdapter.notifyDataSetChanged();
				}
				updateUI();
				relate_foot_show.setEnabled(true);
				progressBar_foot_show.setVisibility(View.GONE);
				tv_foot_show.setText(getText(R.string.add_more));
				break;
			case 2:
				//加载信息fail
				showToast(getText(R.string.loading_fail).toString());
				relate_foot_show.setEnabled(true);
				progressBar_foot_show.setVisibility(View.GONE);
				tv_foot_show.setText(getText(R.string.add_more));
				break;
			case 3:
				//点赞或取消赞成功
				tv_good_num.setText(""+good_num);
			
				updateUI();
				break;
			case 4:
				//点赞或取消赞成失败
				showToast(getText(R.string.fail).toString());
				break;
			case 5:
				//收藏或取消收藏成功
				updateUI();
				break;
			case 6:
				//收藏或取消收藏失败
				showToast(getText(R.string.fail).toString());
				break;
			case 7:
				//发表评论成功
				
				
				
				showToast(getText(R.string.send_success).toString());
				break;
			case 8:
				//发表评论失败
				showToast(getText(R.string.send_fail).toString());
				break;
			case 9:
				//信息为空
				showToast(getText(R.string.info_null).toString());
				break;
			default:
				break;
			}
		};
	};

	ArrayList<PinglunInfo> pingArrayList = new ArrayList<PinglunInfo>();

	// 获取info
	void getInfo() {
		Log.e("tag", "获取info:" + news_id);
		ComyouHttpProgram httpProgram = new ComyouHttpProgram();
		httpProgram.add("news_id", news_id + "");
		ComyouHttpClient httpClient = new ComyouHttpClient(MyConfig.IP
				+ "app/news/news_comment");
		httpClient.postAsync(httpProgram, new ComyouHttpCallBack() {

			@Override
			public void onResponse(String resString) {
				Log.e("RZCinfoActivity", resString);
				try {
					if (pingArrayList != null) {
						pingArrayList.clear();
					}
					JSONObject jsonObject = new JSONObject(resString);
					int status = jsonObject.getInt("err");
					if (status == 0) {
						JSONObject dataObject = jsonObject
								.getJSONObject("data");
						good_num = Integer.parseInt(dataObject.getString("good_num"));
						total_count = Integer.parseInt(dataObject.getString("total_count"));
						int fav_num=dataObject.getInt("my_fav");
						int news_my_dz=dataObject.getInt("news_my_dz");
						if(fav_num==0){
							favFlag=false;
						}else{
							favFlag=true;
						}
						if(news_my_dz==0){
							zanFlag=false;
						}else{
							zanFlag=true;
						}
						
						// 评论
						JSONArray pinglunArray = dataObject
								.getJSONArray("comment");
						if (pinglunArray != null && pinglunArray.length() > 0) {
							for (int i = 0; i < pinglunArray.length(); i++) {
								JSONObject object = (JSONObject) pinglunArray
										.opt(i);
								int user_id=0;
								try {
									user_id = Integer.parseInt(object.getString("user_id"));
								} catch (Exception e) {
								}
								
								String create_time = object
										.getString("create_time");
								String comment_content = object
										.getString("comment_content");
								String name = object.getString("name");
								String tx_img = object.getString("tx_img");
//								int statu = object.getString("status")==null?0: Integer.parseInt(object.getString("status"));;

								PinglunInfo pinglunInfo = new PinglunInfo();
								pinglunInfo.setUser_id(user_id);
								pinglunInfo.setCreate_time(create_time);
								pinglunInfo.setComment_content(comment_content);
								pinglunInfo.setName(name);
								pinglunInfo.setTx_img(tx_img);
								pinglunInfo.setStatus(0);
								pingArrayList.add(pinglunInfo);
							}
						}
						// 点赞
						handler.sendEmptyMessage(1);
					} else {
						handler.sendEmptyMessage(2);
					}

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					handler.sendEmptyMessage(2);
				}

			}

			@Override
			public void onFailure(String arg0, IOException arg1) {
				Log.e("tag", arg0);
				handler.sendEmptyMessage(2);
			}

		});
	}

	/**
	 * 点赞
	 */
	void zanSend(){
		final MyProgressDialog progressDialog=new MyProgressDialog(this);
		progressDialog.setContent(getText(R.string.getting).toString());
		progressDialog.show();
		Log.e("tag", "点赞info:" + news_id);
		ComyouHttpProgram httpProgram = new ComyouHttpProgram();
		httpProgram.add("news_id", news_id + "");
		String value="";
		if(zanFlag){
			value="-1";
		}else{
			value="+1";
		}
		httpProgram.add("str", value);
		ComyouHttpClient httpClient = new ComyouHttpClient(MyConfig.IP
				+ "app/news/new_dz");
		httpClient.postAsync(httpProgram, new ComyouHttpCallBack() {
			
			@Override
			public void onResponse(String resString) {
				progressDialog.dismiss();
				Log.e("RZCJSON", resString);
				try {
					JSONObject jsonObject=new JSONObject(resString);
					int status = jsonObject.getInt("err");
					if (status == 0) {
						zanFlag=!zanFlag;
						if(zanFlag){
							good_num=good_num-1;
						}else{
							good_num=good_num+1;
						}
						handler.sendEmptyMessage(3);
						
						
						
					}else{
						handler.sendEmptyMessage(4);
					}
					
					
					
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					handler.sendEmptyMessage(4);
				}
				
			}
			
			@Override
			public void onFailure(String arg0, IOException arg1) {
				progressDialog.dismiss();
				handler.sendEmptyMessage(4);
			}
		});
		
	}
	/**
	 * 收藏
	 */
	void favSend(){
		final MyProgressDialog progressDialog=new MyProgressDialog(this);
		progressDialog.setContent(getText(R.string.getting).toString());
		progressDialog.show();
		Log.e("tag", "收藏info:" + news_id);
		ComyouHttpProgram httpProgram = new ComyouHttpProgram();
		httpProgram.add("news_id", news_id + "");
		httpProgram.add("user_id", mySharedPreferences.getUserId()+"");
		ComyouHttpClient httpClient = new ComyouHttpClient(MyConfig.IP
				+ "app/news/my_fav");
		httpClient.postAsync(httpProgram, new ComyouHttpCallBack() {
			
			@Override
			public void onResponse(String resString) {
				progressDialog.dismiss();
				Log.e("tag", resString);
				try {
					JSONObject jsonObject=new JSONObject(resString);
					int status = jsonObject.getInt("err");
					if (status == 0) {
						favFlag=!favFlag;
						
						handler.sendEmptyMessage(5);
						
						
						
					}else{
						handler.sendEmptyMessage(6);
					}
					
					
					
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					handler.sendEmptyMessage(6);
				}
				
			}
			
			@Override
			public void onFailure(String arg0, IOException arg1) {
				progressDialog.dismiss();
				handler.sendEmptyMessage(6);
			}
		});
	}
	
	/**
	 * 发送评论
	 */
	String create_time="";
	void sendPingLun(final String str){
		final MyProgressDialog progressDialog=new MyProgressDialog(this);
		progressDialog.setContent(getText(R.string.send).toString());
		progressDialog.show();
		Log.e("tag", "收藏info:" + news_id);
		ComyouHttpProgram httpProgram = new ComyouHttpProgram();
		httpProgram.add("news_id", news_id + "");
		httpProgram.add("user_id", mySharedPreferences.getUserId()+"");
		httpProgram.add("content", str);
		create_time=Util.formatTimeLongToString(System.currentTimeMillis());
		httpProgram.add("create_time",create_time);
		ComyouHttpClient httpClient = new ComyouHttpClient(MyConfig.IP
				+ "app/news/add_comment");
		httpClient.postAsync(httpProgram, new ComyouHttpCallBack() {
			
			@Override
			public void onResponse(String resString) {
				progressDialog.dismiss();
				Log.e("RZCinfoActivity", resString);
				try {
					JSONObject jsonObject=new JSONObject(resString);
					int status = jsonObject.getInt("err");
					if (status == 0) {
						
						PinglunInfo pinglunInfo = new PinglunInfo();
						pinglunInfo.setUser_id(mySharedPreferences.getUserId());
						pinglunInfo.setCreate_time(create_time);
						pinglunInfo.setComment_content(str);
						pinglunInfo.setName(mySharedPreferences.getUserName());
						pinglunInfo.setTx_img(mySharedPreferences.getUserLoginHeadURL());
						pinglunInfo.setStatus(1);
						pinglunInfos.add(pinglunInfo);
						pingLunListAdapter.notifyDataSetChanged();
						handler.sendEmptyMessage(7);
						
						
						
					}else{
						handler.sendEmptyMessage(8);
					}
					
					
					
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					handler.sendEmptyMessage(8);
				}
				
			}
			
			@Override
			public void onFailure(String arg0, IOException arg1) {
				progressDialog.dismiss();
				handler.sendEmptyMessage(8);
			}
		});
	}
	/**
	 * 评论
	 */
	SendPingLunPopwindow sendPingLunPopwindow;
	public void sendSendPingLunPopwindow(){
		sendPingLunPopwindow=new SendPingLunPopwindow(this, new OnClickListenterBack() {
			
			@Override
			public void onClick(String str) {
				sendPingLunPopwindow.dismiss();
				if(str.equals("")){
					handler.sendEmptyMessage(9);
				}else{
					sendPingLun(str);
				}
				
			}
		});
		// 显示窗口
		sendPingLunPopwindow.showAtLocation(
				findViewById(R.id.activityinfo),
				Gravity.BOTTOM, 0, 0); // 设置layout在PopupWindow中显示的位置
	}
	

	/**
	 * 自定义提示
	 * 
	 * @param str
	 */
	Toast toast = null;

	void showToast(String str) {
		if (toast != null) {
			toast.cancel();
		}
		LayoutInflater inflater = getLayoutInflater();
		View view = inflater.inflate(R.layout.toastshow, null);
		TextView textView = (TextView) view.findViewById(R.id.toastshow);
		textView.setText(str);
		toast = new Toast(this);
		double d = getResources().getDisplayMetrics().density;
		toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.CENTER, 0, 0);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(view);
		toast.show();
	}

}
